import React, { Component } from 'react'

export default class Parent extends Component {
  state = {
    hasError: ''
  }
  // 当Parent的子组件出现报错时，会触发getDerivedFromError生命周期钩子，并携带错误信息
  static getDerivedStateFromError(error){
    // 返回的对象直接替换state
    return {hasError: error}
  }
  conponentDidCatch(){
    console.log('组件渲染时出错才会执行！！')
  }
  render() {
    return (
      <div>
        <h1>我是Parent组件</h1>
        {this.state.hasError ? <h2>子组件出错，请排查！</h2> : <Child render={(nameList)=><Child2 nameList={nameList}/>}/>}
      </div>
    )
  }
}
class Child extends Component {
  render() {
    return (
        <div>
            <h1>Child组件</h1>
            {this.props.render('abc')}
        </div>
    )
  }
}
class Child2 extends Component {
    render() {
      return (
        <div>
            <h2>我是Child2组件</h2>
            <div>接收到的数据为：
              <ul>
                {this.props.nameList.map(item=>(<li key={item}>{item}</li>))}
              </ul>
            </div>
        </div>

      )
    }
  }